import axios, { AxiosRequestConfig, AxiosInstance } from 'axios';

// 创建 axios 实例
const createInstance = (config: AxiosRequestConfig): AxiosInstance => {
    const instance = axios.create({
        baseURL: 'http://localhost:8181/api/',
        timeout: 5000,
    });

    // 添加请求拦截器：自动注入 token
    // 前端请求拦截器
    instance.interceptors.request.use(config => {
        const token = sessionStorage.getItem('token'); // 从 sessionStorage 获取 token
        console.log(token);
        if (token) {
            config.headers.Authorization = `Bearer ${token}`; // 设置 Authorization 头
        }
        return config;
    }, error => {
        return Promise.reject(error);
    });

    return instance;
};

// 定义结果接口
export interface Result<T = unknown> {
    msg: string;
    code: number;
    data: T;
}

// 创建实例
const instance = createInstance({});

// get 请求
export const get = <T = any>(url: string, data: any): Promise<Result<T>> => {
    return instance.get(url,data);
};

// post 请求
export const post = <T = any>(url: string, data: any): Promise<Result<T>> => {
    return instance.post(url, data);
};